package es.mgil.soaTest.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;
import es.mgil.soaTest.RestMainActivity;
import es.mgil.soaTest.RestTweetsActivity;

public class RestProgressTask extends AsyncTask<String, Void, Boolean> {

	private ProgressDialog dialog;
	private Context context;
	private String url_tweet, username;

	public RestProgressTask(Context context, String url, String username) {
		this.context = context;
		this.dialog = new ProgressDialog(context);
		this.url_tweet = url;
		this.username = username;
	}

	protected void onPreExecute() {
		this.dialog.setMessage("Leyendo los Tweets de " + this.username);
		this.dialog.show();
	}

	@Override
	protected void onPostExecute(final Boolean success) {
		if (dialog.isShowing()) {
			dialog.dismiss();
		}
		if (success) {
			Toast.makeText(this.context, "Tweets Leidos!", Toast.LENGTH_LONG)
					.show();
			Intent intent = new Intent(this.context.getApplicationContext(),
					RestTweetsActivity.class);
			this.context.startActivity(intent);
		} else {
			Toast.makeText(this.context, "Error en la lectura",
					Toast.LENGTH_LONG).show();
		}
	}

	protected Boolean doInBackground(final String... args) {
		try {
			String read_hashtag = readTwitterFeed(this.url_tweet);
			if (read_hashtag == null) {
				return false;
			}

			JSONArray jsonArray = new JSONArray(read_hashtag);
			RestMainActivity.tweets = new Tweet[jsonArray.length()];
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = (JSONObject) jsonArray.get(i);
				Tweet tweet = new Tweet();
				if (!jsonObject.has("retweeted_status")) {
					tweet.setUser(jsonObject.getJSONObject("user").getString(
							"name"));
					tweet.setTweet(jsonObject.getString("text"));
				} else {
					tweet.setUser(jsonObject.getJSONObject("retweeted_status")
							.getJSONObject("user").getString("name"));
					tweet.setTweet(jsonObject.getString("text"));
				}
				RestMainActivity.tweets[i] = tweet;
			}
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	private String readTwitterFeed(String url) {
		try {
			StringBuilder builder = new StringBuilder();
			HttpClient client = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(url);

			HttpResponse response = client.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} else {
				return null;
			}

			return builder.toString();
		} catch (ClientProtocolException e) {
			return null;
		} catch (IOException e) {
			return null;
		}
	}

}
